#!/usr/bin/env python3
"""
meson 存根生成器

在 meson 构建过程中自动生成类型存根文件。
"""

import os
import sys
import subprocess
from pathlib import Path


def run_libmcpp_extractor(project_root: str, output_dir: str) -> bool:
    """运行 libmcpp 符号提取器"""
    try:
        # 查找 libmcpp 路径
        libmcpp_path = Path(project_root) / 'subprojects' / 'libmcpp'
        if not libmcpp_path.exists():
            print(f"警告: libmcpp 路径不存在: {libmcpp_path}")
            return True  # 不强制要求 libmcpp 存在
        
        # 运行提取器
        extractor_script = Path(project_root) / 'scripts' / 'extract_libmcpp_stubs.py'
        if not extractor_script.exists():
            print(f"警告: libmcpp 提取器脚本不存在: {extractor_script}")
            return True
        
        cmd = [sys.executable, str(extractor_script), str(libmcpp_path), '-o', output_dir]
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if result.returncode == 0:
            print("✓ libmcpp 存根文件生成成功")
            return True
        else:
            print(f"✗ libmcpp 存根文件生成失败: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"错误: 运行 libmcpp 提取器失败: {e}")
        return False


def run_stub_generator(project_root: str, output_dir: str) -> bool:
    """运行存根生成器"""
    try:
        # 确保输出目录存在
        Path(output_dir).mkdir(parents=True, exist_ok=True)
        
        # 运行 libmcpp 提取器
        success = run_libmcpp_extractor(project_root, output_dir)
        
        # TODO: 在这里添加 mdb_interface 提取器
        # success &= run_mdb_interface_extractor(project_root, output_dir)
        
        return success

    except Exception as e:
        print(f"错误: 运行存根生成器失败: {e}")
        return False


def main():
    """主函数"""
    if len(sys.argv) < 3:
        print("用法: python meson_stub_generator.py <project_root> <output_dir>")
        sys.exit(1)

    project_root = sys.argv[1]
    output_dir = sys.argv[2]

    print(f"开始生成存根文件...")
    print(f"项目根目录: {project_root}")
    print(f"输出目录: {output_dir}")

    success = run_stub_generator(project_root, output_dir)
    
    if success:
        print("✓ 存根文件生成完成")
    else:
        print("✗ 存根文件生成失败")
    
    sys.exit(0 if success else 1)


if __name__ == '__main__':
    main() 